package com.wenzhi.studentservice.service.impl;

import com.wenzhi.studentservice.dto.StudentAddDTO;
import com.wenzhi.studentservice.dto.StudentListDTO;
import com.wenzhi.studentservice.dto.StudentUpdateDTO;
import com.wenzhi.studentservice.entity.StudentEntity;
import com.wenzhi.studentservice.service.IStudentService;
import com.wenzhi.studentservice.vo.StudentListVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class StudentServiceImpl implements IStudentService {
    // 模拟数据库
    private List<StudentEntity> students = new ArrayList<>();

    {
        StudentEntity student = new StudentEntity();
        student.setName("tom");
        student.setAge(18);
        student.setGender("女");
        student.setClazz("二班");
        student.setPassword("123456");
        student.setId(System.currentTimeMillis());
    }

    // ctrl+i 实现方法
    @Override
    public List<StudentListVO> list(StudentListDTO dto) {
        List<StudentListVO> vos = new ArrayList<>();
        // stream // 循环
        for (StudentEntity student : students) {
            if (StringUtils.hasText(dto.getName())) {
                if (!Objects.equals(student.getName(), dto.getName())) {
                    continue;
                }
            }

            if (Objects.nonNull(dto.getAge())) {
                if (!Objects.equals(student.getAge(), dto.getAge())) {
                    continue;
                }
            }
            StudentListVO vo = new StudentListVO(); // 少密码字段
            // 源对象 目标对象 // 对象属性值复制
            BeanUtils.copyProperties(student, vo);
            vos.add(vo);
        }
        return vos;
    }

    @Override
    public Long add(StudentAddDTO dto) {
        StudentEntity student = new StudentEntity();
        BeanUtils.copyProperties(dto, student);
        student.setId(System.currentTimeMillis());
        student.setPassword("123456");
        students.add(student);
        return student.getId();
    }

    @Override
    public boolean update(StudentUpdateDTO dto) {
        for (StudentEntity student : students) {
            if (Objects.equals(student.getId(), dto.getId())) {
                BeanUtils.copyProperties(dto, student);
                return true;
            }
        }
        return false;
    }
}
